OpenCV Load Image (cv2.imread)

您所在的位置:网站首页 screen write OpenCV Load Image (cv2.imread)

OpenCV Load Image (cv2.imread)

2023-06-20 02:02| 来源: 网络整理| 查看: 265

Click here to download the source code to this post

In this tutorial, you will learn how to use OpenCV and the cv2.imread function to:

Load an input image from diskDetermine the image’s width, height, and number of channelsDisplay the loaded image to our screenWrite the image back out to disk as a different image filetype

By the end of this guide, you will have a good understanding of how to load images from disk with OpenCV.

A dataset of images is essential to practice and understand the operation of the OpenCV library. It allows us to deal with images of different formats and sizes, thus broadening our understanding of how to manipulate images using OpenCV.

Roboflow has free tools for each stage of the computer vision pipeline that will streamline your workflows and supercharge your productivity.

Sign up or Log in to your Roboflow account to access state of the art dataset libaries and revolutionize your computer vision pipeline.

You can start by choosing your own datasets or using our PyimageSearch’s assorted library of useful datasets.

Bring data in any of 40+ formats to Roboflow, train using any state-of-the-art model architectures, deploy across multiple platforms (API, NVIDIA, browser, iOS, etc), and connect to applications or 3rd party tools.

To learn how to load an image from disk using OpenCV and cv2.imread, just keep reading.

Looking for the source code to this post? Jump Right To The Downloads Section OpenCV load image (cv2.imread)

In the first part of this tutorial, we’ll discuss how to load an image from disk using OpenCV and the cv2.imread function.

From there, you’ll learn how to configure your development environment to install OpenCV.

We will then review our project directory structure, followed by implementing load_image_opencv.py, a Python script that will load input images from disk using OpenCV and the cv2.imread function.

We’ll wrap up this tutorial with a discussion of our results.

How do we load images from disk with OpenCV? Figure 1: To load an image from disk with OpenCV, we can use the cv2.imread function.

To load an input image from disk using OpenCV, we must use the cv2.imread function (Figure 1).

The cv2.imread function accepts a single parameter, the path to where your image lives on your disk:

image = cv2.imread("path/to/image.png")

The OpenCV cv2.imread function then returns either of two values:

A NumPy array representing the image with the shape (num_rows, num_cols, num_channels), which we’ll discuss later in this tutorial A NoneType object, implying that the image could not be loaded

Typically, the cv2.imread function will return None if the path to the input image is invalid, so be sure to double-check and triple-check your input image paths! The function will also fail for unsupported image file types, although OpenCV can read a wide variety of them, including JPEG, PNG, TIFF, and GIF.

Let’s see how to obtain the OpenCV library before putting the cv2.imread function into action.

Configuring your development environment

Before digging into image loading with OpenCV, you’ll need to have the library installed on your system.

Luckily, OpenCV is pip-installable:

$ pip install opencv-contrib-python

If you need help configuring your development environment for OpenCV 4.3+, I highly recommend that you read my pip install OpenCV guide — it will have you up and running in a matter of minutes.

Having problems configuring your development environment? Screenshot of PyImageSearch Plus and Google Colab Notebook with Jupyter logo overlaidFigure 2: Having trouble configuring your dev environment? Want access to pre-configured Jupyter Notebooks running on Google Colab? Be sure to join PyImageSearch Plus — you’ll be up and running with this tutorial in a matter of minutes.

All that said, are you:

Short on time?Learning on your employer’s administratively locked system?Wanting to skip the hassle of fighting with the command line, package managers, and virtual environments?Ready to run the code right now on your Windows, macOS, or Linux systems?

Then join PyImageSearch Plus today!

Gain access to Jupyter Notebooks for this tutorial and other PyImageSearch guides that are pre-configured to run on Google Colab’s ecosystem right in your web browser! No installation required.

And best of all, these Jupyter Notebooks will run on Windows, macOS, and Linux!

Project structure

Let’s review our project structure. Grab the source code from the “Downloads” section, unzip the content, and navigate to where you saved it:

$ tree . --dirsfirst . ├── 30th_birthday.png ├── jurassic_park.png ├── load_image_opencv.py └── newimage.jpg 0 directories, 4 files

Our project contains a single Python script named load_image_opencv.py and a couple of test images.

In our script, we’ll first load an image from disk using the OpenCV cv2.imread function and then display it on screen for assessment. Finally, we’ll save the displayed image back to disk with OpenCV as a new file named newimage.jpg.

Let’s now implement our image-loading Python script using OpenCV!

Implementing our OpenCV image loading script

Let’s get started learning how to load an input image from disk using OpenCV.

Create a Python script named load_image_opencv.py, and insert the following code:

# import the necessary packages import argparse import cv2 # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="path to input image") args = vars(ap.parse_args())

Start by importing the Python utility package argparse for command line arguments parsing on Line 2 and the OpenCV library on Line 3.

Notice that the OpenCV developers adopted the name cv2 from version 2.0 of the library and kept this naming convention regardless of the release we’re using (e.g., 3.x, 4.x). We’ll be using the latest version 4.3+ installed as detailed in the previous section.

The argparse package allows us to pass dynamic arguments to our Python script such that we do not have to hardcode parameter variables that need to be manually changed every time we’d like to alter their values.

If you are unfamiliar with how the argparse package works, be sure to read my tutorial on the subject.

Lines 6-9 set up our command line argument parser with a single argument containing the path to our input --image. We set the argument as required, ensuring that a value must always be passed when invoking our Python script.

With our input --image path dynamically defined, it’s now easy to load the image using OpenCV:

# load the image from disk via "cv2.imread" and then grab the spatial # dimensions, including width, height, and number of channels image = cv2.imread(args["image"]) (h, w, c) = image.shape[:3] # display the image width, height, and number of channels to our # terminal print("width: {} pixels".format(w)) print("height: {} pixels".format(h)) print("channels: {}".format(c))

OpenCV makes reading a wide range of image file types from disk a breeze with the cv2.imread function.

We load the input --image to memory on Line 13 using cv2.imread, which returns the image as a NumPy array. Upon success, we obtain the image dimensions (h, w, c) from the shape of the array (Line 14) — I’ll provide more information about caveats regarding this line of code later.

We can now print the image dimensions (width, height, and number of channels) to the terminal for review (Lines 18-20).

In a future blog post, we’ll talk about what image channels are, but for now keep in mind that the number of channels will be three for color images, representing the Red, Green, and Blue (RGB) components of pixel colors.

But hey, what good is it having an image in memory if we do not know whether it was read correctly by OpenCV? Let’s display the image on screen for verification:

# show the image and wait for a keypress cv2.imshow("Image", image) cv2.waitKey(0) # save the image back to disk (OpenCV handles converting image # filetypes automatically) cv2.imwrite("newimage.jpg", image)

The cv2.imshow OpenCV function is very convenient here, as it displays an image on our screen using only two parameters (Line 23). The first is a string representing the name assigned to the window that will be opened to hold the figure; the second is the image we want to display.

From there, we need to call the cv2.waitKey function to keep the window opened until a key is pressed (Line 24). This function receives a single parameter corresponding to the time delay (in milliseconds) used to keep the window alive if no key is pressed. The parameter value 0 instructs the cv2.waitKey function to wait indefinitely.

Finally, Line 28 saves the image back to disk. The OpenCV cv2.imwrite function accepts a filename as the first parameter and the image as the second.

The cv2.imwrite function saves a file named “newimage.jpg” that automatically converts the image to JPG format based on the filename extension.

You should now be able to apply OpenCV to:

Load an image from diskDisplay it on screenWrite it back to disk

We’ll review some of the results of those operations in the next section.

OpenCV image loading results

Now it’s time to load images from the disk using OpenCV!

Start by accessing the “Downloads” section of this tutorial to retrieve the source code and example images.

From there, open a terminal, and execute the following command:

$ python load_image_opencv.py --image 30th_birthday.png width: 720 pixels height: 764 pixels channels: 3 Figure 3: Loading an image from disk using OpenCV and cv2.imread.

For my 30th birthday a couple of years ago, my wife rented a near-replica jeep from Jurassic Park (my favorite movie) for us to drive around for the day.

In Figure 3, you can see that our input image, 30th_birthday.png, has been loaded from disk using OpenCV and then displayed to your screen.

This image has a width of 720 pixels, a height of 764 pixels, and three channels (one for each Red, Green, and Blue channel, respectively).

Additionally, if you check the contents of our project directory after running the script, you will see a file named newimage.jpg:

$ ls 30th_birthday.png jurassic_park.png load_image_opencv.py newimage.jpg

This image was saved to disk via OpenCV using the cv2.imwrite function.

Note that while the 30th_birthday.png image was a PNG file type, OpenCV has automatically converted the image to a JPG file type for us.

Let’s try another image:

$ python load_image_opencv.py --image jurassic_park.png width: 577 pixels height: 433 pixels channels: 3 Figure 4: OpenCV image loading with cv2.imread.

Continuing on with the Jurassic Park theme in this tutorial, here we have a photo of Ray Arnold (played by Samuel L. Jackson).

This image has a width of 577 pixels, a height of 433 pixels, and three channels.

If you’re brand-new to OpenCV, I suggest you now take the time to play around with the cv2.imread function. Specifically, experiment with:

Loading your own images via cv2.imread Trying various image file types and noting which ones OpenCV does/does not support Purposely passing incorrect file paths to cv2.imread (i.e., what does cv2.imread return if the input image path is valid)

Speaking of that final bullet item, let’s give that a try now …

What happens if we pass an invalid image path to “cv2.imread”?

You might be wondering what happens if we pass an invalid file path (meaning the path to the input image does not exist on disk) to OpenCV and cv2.imread?

Let’s find out:

$ python load_image_opencv.py --image path/does/not/exist.png Traceback (most recent call last): File "load_image_opencv.py", line 17, in (h, w, c) = image.shape[:3] AttributeError: 'NoneType' object has no attribute 'shape'

Here I am purposely providing an image path that does not exist on my disk.

When I pass an invalid image path to OpenCV’s cv2.imread function, cv2.imread returns None.

And when I try to grab the image width, height, and number of channels, Python errors out with an AttributeError, saying that the NoneType object does not have a shape attribute.

This error makes sense when you think about it:

If you supply an invalid image path to cv2.imread, the function will return None. However, our code assumes the image path is correct and thus returns a NumPy array. But if the returned image is None, then it is not a valid NumPy array, hence the error.

Anytime you see these None or NoneType errors, your first step in diagnosing and resolving them is to investigate whether your image was successfully read from disk correctly. 99% of the time the error is due to your code assuming a valid image, but in fact the image was not properly read from disk!

What's next? I recommend PyImageSearch University. Course information: 77 total classes • 96 hours of on-demand code walkthrough videos • Last updated: June 2023 ★★★★★ 4.84 (128 Ratings) • 16,000+ Students Enrolled

I strongly believe that if you had the right teacher you could master computer vision and deep learning.

Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?

That’s not the case.

All you need to master computer vision and deep learning is for someone to explain things to you in simple, intuitive terms. And that’s exactly what I do. My mission is to change education and how complex Artificial Intelligence topics are taught.

If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to successfully and confidently apply computer vision to your work, research, and projects. Join me in computer vision mastery.

Inside PyImageSearch University you'll find:

✓ 77 courses on essential computer vision, deep learning, and OpenCV topics ✓ 77 Certificates of Completion ✓ 96 hours of on-demand video ✓ Brand new courses released regularly, ensuring you can keep up with state-of-the-art techniques ✓ Pre-configured Jupyter Notebooks in Google Colab ✓ Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!) ✓ Access to centralized code repos for all 508+ tutorials on PyImageSearch ✓ Easy one-click downloads for code, datasets, pre-trained models, etc. ✓ Access on mobile, laptop, desktop, etc.

Click here to join PyImageSearch University

Summary

In this tutorial, you learned how to load images using OpenCV and the cv2.imread function.

We created a Python script to:

Load an image from disk as a NumPy array using the cv2.imread function Display the image on screen with cv2.imshow Save the image back to disk with cv2.imwrite

OpenCV conveniently handles reading and writing a wide variety of image file formats (e.g., JPG, PNG, TIFF). The library also simplifies displaying an image on screen and allowing user interaction with the opened window.

If an image cannot be read by OpenCV, you should carefully check if the input filename was given correctly, as the cv2.imread function returns a NoneType Python object upon failure. The function will fail if the file does not exist or if the image format is unsupported by OpenCV.

We have also printed the image dimensions to the terminal (width, height, and number of channels), based on the values of the underlying NumPy array shape. Our script then saved the image to disk using the JPG format, taking advantage of OpenCV’s ability to automatically convert the image to the desired file type.

In the next tutorial in this series, you will learn about OpenCV image basics, including what a pixel is, an overview of the image coordinate system, and how to access individual pixel values.

To download the source code to this post (and be notified when future tutorials are published here on PyImageSearch), simply enter your email address in the form below!

Download the Source Code and FREE 17-page Resource Guide

Enter your email address below to get a .zip of the code and a FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning. Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3